<?php
declare(strict_types=1);
namespace app\install\controller;
use aphp\core\Jump;
use aphp\core\Tool;
/**
 * 还原安装
 */
class Index
{
    use Jump;
    protected string $check_table = 'user'; // 检测表，存在则已安装

    public function index()
    {
        if ($this->isPost()) {
            $backup_path = Tool::dir_init(ROOT_PATH . '/backup', 0777);
            $db = db();
            $lock_file = $backup_path . '/install.lock';
            $now = date('Y-m-d H:i:s');
            if (empty($this->check_table)) {
                $this->error('未设置检测表名！');
            }
            if ($db->hasTable($this->check_table)) {
                file_put_contents($lock_file, $now);
                $this->error('检测到数据库表已存在，重装需清空数据库，或进入后台还原。');
            }
            $path = input('post.path', '', 'clear_html');
            if (empty($path)) {
                $this->error('请输入备份文件夹名');
            }
            if (!is_dir(ROOT_PATH . '/backup/' . $path)) {
                $this->error('备份文件夹不存在');
            }
            $glob = @glob(ROOT_PATH . '/backup/' . $path . '/*.sql');
            sort($glob);
            foreach ($glob as $file) {
                $data = file_get_contents($file);
                $data = mb_convert_encoding($data, 'UTF-8', 'auto');
                $sqlList = explode('-- <fen> --', $data);
                if (count($sqlList) > 1) {
                    array_pop($sqlList);
                }
                foreach ($sqlList as $sql) {
                    $db->noLog()->execute($sql);
                }
                usleep(100000);
            }
            file_put_contents($lock_file, $now);
            $this->success('安装成功!默认管理员：admin 密码：admin', 'index/index');
        }
        return view();
    }
}